/** 对应 stack/expression.js算术表达式题目，自己练习 */

const max = 9999999;

function e(str, l, r) {
  let pos = -1;
  let level = max - 1;
  let por = 0; // 优先级的基数
  for(let i = l;i<r;i++) {
    const cur = str[i];
    let curl = max;
    switch(cur) {
      case "(":
        por += 100;
        break;
      case ")":
        por -= 100;
        break;
      case "+":
      case "-": curl = por + 1; break;
      case "*":
      case "/": curl = por + 2; break;
    }
    if (curl <= level) {
      pos = i;
      level = curl;
    }
  }
  if (pos == -1) {
    return Number(str.slice(l, r + 1).replace("(", "").replace(")", ""));
  }
  const lefeVal = e(str, l, pos - 1);
  const rightVal = e(str, pos + 1, r);
  switch(str[pos]) {
    case "+": return lefeVal + rightVal;
    case "-": return lefeVal - rightVal;
    case "*": return lefeVal * rightVal;
    case "/": return lefeVal / rightVal;
  }
}

function expression(str) {
  console.info(e(str, 0, str.length - 1))
  // e(str, 0, str.length - 1)
}

expression("3*4+5");
expression("3*(4+5)");